package com.app.service.impl;

import com.app.common.SystemConstant;
import com.app.mapper.FileMapper;
import com.app.model.FileModel;
import com.app.service.FileService;
import com.app.utils.CommonHelp;
import com.app.utils.CommonUtil;
import com.app.vo.FileVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, FileModel> implements FileService {
    @Autowired
    private FileMapper fileMapper;

    @Override
    public FileVo getFileList(Integer page, Integer limit, Integer type, Integer moduleId,Integer businessId) {
        Page<FileModel> page1 = new Page<>(page, limit);
        QueryWrapper<FileModel> qw = new QueryWrapper<>();
        if (type == 1 || type == 2) {
            qw.eq("file_type", type);
        }
        qw.eq(moduleId!=null,"module_id", moduleId);
        qw.eq(businessId!=null,"business_id", businessId);
        qw.orderByDesc("create_time").or().orderByDesc("id");
        Page<FileModel> filePage = fileMapper.selectPage(page1, qw);
        List<FileModel> fileList = filePage.getRecords();
        for (int i = 0; i < fileList.size(); i++) {
            fileList.get(i).setUrl(SystemConstant.DEFAULT_PDF_SERVICE_URL + fileList.get(i).getName());
        }
        long count = filePage.getTotal();
        FileVo FileVo = new FileVo();
        FileVo.setList(fileList);
        FileVo.setCount((int) count);
        return FileVo;
    }

    @Override
    public StringBuilder uriListToIdList(StringBuilder idList, List<String> urlList) {
        int count=0;
        for (String url : urlList) {
            //获取文件名称fileName
            String[] split = url.split("/");
            String fileName = split[split.length - 1];
            //获取URL后缀名urlSuffix
            int lastIndexOf = url.lastIndexOf(".");
            String urlSuffix = url.substring(lastIndexOf + 1);

            FileModel fileModel = new FileModel();
            fileModel.setName(fileName);
            fileModel.setUrl(url);
            Integer fileType = CommonUtil.getFileType(urlSuffix);
            fileModel.setFileType(fileType);

            fileModel.setCreateTime(CommonHelp.getNowTimestamp());
            fileMapper.insert(fileModel);
            if (count == urlList.size()-1) {
                idList.append(fileModel.getId());
            } else {
                idList.append(fileModel.getId()).append(",");
            }
            count++;
        }
        return idList;
    }
}
